$.ajaxSetup({
	beforeSend: function() {
		$('.ajax-loader').show();
	},
	complete: function() {
		$('.ajax-loader').hide();
	}
});

/*
 * Handle resizing of content div to fit window on load and resize
 *
 */
$(function() {
	$(window).load(resize).resize(resize);
});
function resize() {
	var windowHeight  = $(window).height();
	var toolBarHeight = $('.toolbar').height();
	var headerHeight  = $('#header').height();
	var contentHeight = windowHeight - headerHeight - 5;
	var navbarHeight  = windowHeight - headerHeight - 5;
	var contentWithToolBarHeight = windowHeight - headerHeight - toolBarHeight - 22;
	var contentWithBreadcrumbHeight = contentWithToolBarHeight - 31;
	$('.content').height(contentHeight);
	$('#navbar, .sidebar').height(navbarHeight);
	$('.content-below-toolbar').height(contentWithToolBarHeight);
	$('.content-below-breadcrumb').height(contentWithBreadcrumbHeight);
	$('iframe.content-below-toolbar').height(contentWithToolBarHeight-4);
	$('.table-data').height(contentWithToolBarHeight-45);
}

/*
 * Update timeout counter
 *
 */
var timeout;
function updateTimeout() {
	var timeoutHours   = Math.floor(timeout/3600);
	var timeoutMinutes = Math.floor(timeout%3600/60);
	if (timeoutMinutes < 10) timeoutMinutes = '0' + timeoutMinutes;
	var timeoutSeconds = timeout%60;
	if (timeoutSeconds < 10) timeoutSeconds = '0'+timeoutSeconds;
	var style;
	if (timeout < 600) {
		$('#timeout').html('<span style="color:' + (timeout < 60 ? 'red' : 'black') + '"> - ' + (timeoutHours ? (timeoutHours + ':') : '') + timeoutMinutes + ':' + timeoutSeconds + '</span>');
	} else {
		$('#timeout').html('');
	}
	timeout--;
	if (timeout > -1) setTimeout("updateTimeout()", 1000);
	else {
		$.blockUI({ message: $('#ajax-login'), css: { width: '532px', left: ($(window).width()/2)-266 } });
		$('#ajax-login .messages').hide();
		$('#timeout').html('');
	}
}	

function syncTimeout(reset, initial) {
	if (typeof(reset) == 'undefined') { reset = false; }
	if (typeof(initial) == 'undefined') { initial = false; }
	$.get('/admin/timeout/', { reset: reset }, function(resultJson) {
		timeout = resultJson.timeout;
		setTimeout("syncTimeout(false, false)", 60000);
		if (initial) { updateTimeout(); }
	}, 'json');
}
$(function() { 
	if ($('#timeout').length) syncTimeout(false, true);
	$('#timeout').click(function() { syncTimeout(true, false); });
	$('#ajax-login form').submit(function(e) {
		e.preventDefault();
		$('#ajax-login form').ajaxSubmit({ success: function(responseText, statusText) {
			if (responseText == 'OK') {
				syncTimeout(true, true);
				$.unblockUI();
			} else {
				$('#ajax-login .messages').show();
			}
		}});
	});
});

/*
 * Add sorting links to table headers
 *
 */
$(function() {
	$('table.table tr th.sortable').livequery(function() {
		if (!$(this).find('.sort-up').length) {
			var column = $(this).attr('class').substr($(this).attr('class').search(/col_/)).replace(/ .*/, '').replace(/^col_/, '');
			$(this).append(' <a href="?paging[order]='+column+'" class="sort-up"><img src="/admin/backend/resources/images/sort_up.png" /></a><a href="?paging[order]='+column+'+desc" class="sort-down"><img src="/admin/backend/resources/images/sort_down.png" /></a>');
		}
	});
});


/*
 * Delete icon
 *
 */
$(function() {
	$('table.table .delete').livequery(function() {
		$(this).hover(
			function() {
				$(this).parent().parent().addClass('hover-delete');
			},
			function() {
				$(this).parent().parent().removeClass('hover-delete');
			}
		);
	});
	$('table.table .delete').livequery('click', function(e) {
		e.preventDefault();
		var userrow = $(this).parent().parent();
		if (confirm('Are you sure you want to remove this ' + $(this).attr('rel') + '?')) {
			$.post($(this).attr('href'), function() {
				if (userrow.find('th').length) {
					$.get('?', { 'paging[page]': 1 });
				} else {
					userrow.fadeOut(function() { $(this).remove(); $('table.table tr').removeClass('alt'); $('table.table tr:odd').addClass('alt'); $.get('?', insertTableHeaders); });
				}
			});
		}
	});
});

/*
 * Table filtering
 *
 */
var filterTimeout;
$(function() {
	$('.filter').livequery('keyup', function() {
		clearTimeout(filterTimeout);
		$('.filter').val($(this).val());
		filterTimeout = setTimeout("$.get('?paging[page]=1&paging[filter]=" + escape($('.filter').val()) + "', insertTableHeaders);", 250);
	});
});

/*
 * And add Ajaxification for sorting, prev/next, results per page, and tag lists
 *
 */
$(function() {
	$('.sort-up, .sort-down, .page-prev a, .page-next a, .results-per-page a, .tag-list a').livequery('click', function(e) {
		e.preventDefault();
		$.get($(this).attr('href'));
	});
});

/*
 * Add copies of the header every 50 rows
 *
 */
function insertTableHeaders() {
	var header = $('table.table.data thead tr:first');
	var i = 1;
	var total = $('table.table.data tbody tr').length;
	$('table.table.data tbody tr').each(function() {
		if (i % 50 == 0 && i != total) {
			$(this).after(header.clone());
		}
		i++;
	});
}
$('table.table.data tbody tr:first').livequery(insertTableHeaders);



$(function() {
	$("div.tabs").livequery(function() {
		$(this).tabs();
		$(this).bind('tabsselect', function(e, ui) {
			$('.richtext').each(function() { tinyMCE.execCommand('mceRemoveControl', false, $(this).attr('id')); });
			initTinyMce();
			setTimeout("resize();", 500);
		});
	});
});

/*
 * Prevent all toolbar buttons from acting as links
 *
 */
$('.toolbar a').livequery('click', function(e) {
	e.preventDefault();
});

/*
 * Link header save button to form.
 *
 */
$(function() {
	$('a.save:not(.disabled)').livequery('click', function(e) {
		e.preventDefault();
		tinyMCE.triggerSave();
		$.blockUI({ overlayCSS: { opacity: '0.2' }, css: { padding: '15px' } });
		$('.blockMsg').hide();
		$('form.ajax:visible').ajaxSubmit(function() {
			$('a.save').addClass('disabled');
			$('a.publish').removeClass('disabled');
			$.unblockUI();
		});
	});	
});	


$(function() {
	$('form.ajax').livequery(function() {
		$(this).ajaxForm();
	});
});

/*
 * Make any a.ajax links do their ajax thing
 *
 */
$(function() {
	$('a.ajax').livequery('click', function(e) {
		e.preventDefault();
		$.get($(this).attr('href'));
	});
});
$(function() {
	$('a.ajax-post').livequery('click', function(e) {
		e.preventDefault();
		$.post($(this).attr('href'));
	});
});

var tinyMCE;
function initTinyMce() {
	tinyMCE.init({
		// General options
		mode : "specific_textareas",
		editor_selector : "richtext",
		theme : "advanced",
		plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

		// Theme options
		theme_advanced_buttons1 : "code,|,fullscreen,|,template,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,|,pastetext,pasteword,|,bullist,numlist,|,outdent,indent,hr,|,link,unlink,image,media",
		theme_advanced_buttons2 : "tablecontrols",
		theme_advanced_buttons3 : "",
		theme_advanced_buttons4 : "",
		//theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
		//theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
		//theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
		//theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,

		// Example content CSS (should be your site CSS)
		content_css : home_dir + "/tinymce.css",

		// Drop lists for link/image/media/template dialogs
		template_external_list_url : "/admin/tinymce/template_list/",
		external_link_list_url : "/admin/tinymce/link_list/",
		external_image_list_url : "/admin/tinymce/image_list/",
		media_external_list_url : "/admin/tinymce/media_list/",
		relative_urls : false,
		
		onchange_callback : pageChanged,
		
		valid_elements : "@[id|class|style|title|dir<ltr?rtl|lang|xml::lang|onclick|ondblclick|"
		+ "onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|"
		+ "onkeydown|onkeyup],a[rel|rev|charset|hreflang|tabindex|accesskey|type|"
		+ "name|href|target|title|class|onfocus|onblur],strong/b,em/i,strike,u,"
		+ "#p[align],-ol[type|compact],-ul[type|compact],-li,br,img[longdesc|usemap|"
		+ "src|border|alt=|title|hspace|vspace|width|height|align],-sub,-sup,"
		+ "-blockquote,-table[border=0|cellspacing|cellpadding|width|frame|rules|"
		+ "height|align|summary|bgcolor|background|bordercolor],-tr[rowspan|width|"
		+ "height|align|valign|bgcolor|background|bordercolor],tbody,thead,tfoot,"
		+ "#td[colspan|rowspan|width|height|align|valign|bgcolor|background|bordercolor"
		+ "|scope],#th[colspan|rowspan|width|height|align|valign|scope],caption,-div,"
		+ "-span,-code,-pre,address,-h1,-h2,-h3,-h4,-h5,-h6,hr[size|noshade],-font[face"
		+ "|size|color],dd,dl,dt,cite,abbr,acronym,del[datetime|cite],ins[datetime|cite],"
		+ "object[classid|width|height|codebase|*],param[name|value|_value],embed[type|width"
		+ "|height|src|*],script[src|type],map[name],area[shape|coords|href|alt|target],bdo,"
		+ "button,col[align|char|charoff|span|valign|width],colgroup[align|char|charoff|span|"
		+ "valign|width],dfn,fieldset,form[action|accept|accept-charset|enctype|method],"
		+ "input[accept|alt|checked|disabled|maxlength|name|readonly|size|src|type|value],"
		+ "kbd,label[for],legend,noscript,optgroup[label|disabled],option[disabled|label|selected|value],"
		+ "q[cite],samp,select[disabled|multiple|name|size],small,"
		+ "textarea[cols|rows|disabled|name|readonly],tt,var,big,"
		+ "iframe[align<bottom?left?middle?right?top|class|frameborder|height|id"
		+ "|longdesc|marginheight|marginwidth|name|scrolling<auto?no?yes|src|style"
		+ "|title|width]"
		
		
	});
}

/*
 * Catch any regular form field changes
 *
 */
$(function() {
	$('.form input, .form textarea, .form select').livequery('focus', function() {
		if($(this).is(':checkbox') || $(this).is(':radio')) {
			$(this).data('last_val', $(this).is(':checked'));
		} else {
			$(this).data('last_val', $(this).val());
		}
	});
	var triggerChange = function() {
		if($(this).is(':checkbox') || $(this).is(':radio')) {
			if ($(this).data('last_val') != $(this).is(':checked')) pageChanged();
		} else {
			if ($(this).data('last_val') != $(this).val()) pageChanged();
		}
	};
	$('.form input, .form textarea, .form select').livequery('keyup', triggerChange);
	$('.form input, .form textarea, .form select').livequery('change', triggerChange);
});

var pageHasChanged = false;
function pageChanged() {
	$('a.save').removeClass('disabled');
	$('a.publish').addClass('disabled');
	pageHasChanged = true;
	
}

RegExp.escape = function(text) {
	if (!arguments.callee.sRE) {
		var specials = [
			'$', '/', '.', '*', '+', '?', '|',
			'(', ')', '[', ']', '{', '}', '\\'
		];
		arguments.callee.sRE = new RegExp(
			'(\\' + specials.join('|\\') + ')', 'g'
		);
	}
	return text.replace(arguments.callee.sRE, '\\$1');
}

// set this up here, to avoid undefined errors
var swfu_settings = {};

$(function() {
	$('.sidebar').resizable({
		minWidth: 216,
		handles: 'e'
	});
});

// handle the tab madness
$(function() {
	$('*').keyup(function(e) {
		if (e.keyCode == 9) {
			window.scroll(0,0);
		}
	});
});

$(function() {
	$('a.fancybox').livequery(function() {
		$(this).fancybox();
	});
});
